package com.baidu.tcpChatDemo2;

import java.io.*;
import java.net.Socket;

public class ChartServerReaderThread extends Thread{
    private Socket socket;

    public ChartServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String msg;
            while ((msg = bufferedReader.readLine()) != null){
                System.out.println("服务端收到" + socket.getRemoteSocketAddress() +"的消息" + msg);

                //然后将消息转发给所有人
                sengMsgToAll(msg);
            }
        } catch (Exception e) {
            System.out.println(socket.getRemoteSocketAddress() + "已下线");
            ChartServer.sockets.remove(socket);
        }
    }

    private void sengMsgToAll(String msg) throws Exception {
        for (Socket socketTmp : ChartServer.sockets) {
            OutputStream outputStream = socketTmp.getOutputStream();
            PrintStream printStream = new PrintStream(outputStream);
            printStream.println(msg);
            printStream.flush();
        }
    }
}
